const canvas = document.getElementById("canvas1") as HTMLCanvasElement;
const ctx = canvas.getContext("2d") as CanvasRenderingContext2D;
const btn = document.querySelector("button") as HTMLButtonElement;
const img = new Image();
img.src = "../images/lamp.jpg";
img.onload = function () {
  // 可以使图片 ,canvas对象
  // 利用canvas控制图片大小 然后填充
  // 创建一个新的 canvas 元素
  const tempCanvas = document.createElement("canvas");
  const tempCtx = tempCanvas.getContext("2d") as any;

  // 设置临时 canvas 的大小
  tempCanvas.width = 50;
  tempCanvas.height = 34;

  // 在临时 canvas 上绘制图片
  tempCtx.drawImage(img, 0, 0, 50, 34);

  var pat = ctx.createPattern(tempCanvas, "repeat");
  ctx.fillStyle = pat as any;
  ctx.rect(0, 0, 200, 200);
  ctx.fill();

  // 可以直接绘制图片
  //   var pat = ctx.createPattern(img, "repeat");
  //   ctx.rect(0, 0, 600, 400);
  //   ctx.fillStyle = pat as any;
  //   ctx.fill();
};


// 缩放图片
const image = new Image();
image.src = "../images/Hydrangeas.jpg";
let scaleIndex = 1;
btn.onclick = function () {
  scaleIndex -= 0.1;
  if (scaleIndex <= 0) scaleIndex = 0.1; // Prevent scaling to zero or negative
  drawImage();
};

image.onload = function () {
  drawImage();
};

function drawImage() {
  // Clear the canvas
  // ctx.clearRect(200, 500, canvas.width, canvas.height);

  // Save the current context state
  ctx.save();

  // Apply the scaling transformation
  ctx.scale(scaleIndex, scaleIndex);

  // Draw the image
  // Adjust the position based on the scale to keep it centered
  const x = (canvas.width / scaleIndex - 200) / 2;
  const y = (canvas.height / scaleIndex - 200) / 2;
  ctx.drawImage(image, 0, 0, 1024, 768, x, y, 200, 200);

  // Restore the context to its original state
  ctx.restore();
}
